package com.kele.controller;

import com.kele.dao.UserDao;
//import com.kele.domain.Result;
import com.kele.domain.User;
import com.kele.service.UserService;
import com.kele.utils.ResponseData;
import io.swagger.annotations.*;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


/**
 * @author 赵奥林
 * @date 2021年05月10日 13:05
 * @Description 用户的基本操作：登陆注册、增删改查、修改密码、找回密码、修改个人信息、注销账号
 *
 * 接口使用@RestController  相当于 @ResponseBody + @Controller
 */
@Controller
@RequestMapping("/user")
@Api(value = "用户模块", tags = {"用户管理操作接口"})
public class UserController {

    @Resource
    private UserService userService;


    /**
     * 用户登录
     * @param account
     * @param password
     * @param request
     * @return 登陆成功返回数据，登陆失败则返回提示信息
     */
    @RequestMapping(value = "/loginAccount", method = RequestMethod.POST)
    @ApiOperation(value = "用户登录", notes = "根据校验用户名和密码来进行登录")
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "account", value = "用户账户", required = true, paramType = "query"),
            @ApiImplicitParam(name = "password", value = "用户密码", required = true, paramType = "query")
    })
    public ResponseData<User> loginAccount(String account,
                                           String password,
                                           HttpServletRequest request) {
        if (account != null && account != "") {
            User user = userService.loginUser(account, password);
            if (user != null) {
                request.getSession().setAttribute("User", user);
                if (request.getSession().getAttribute("User") != null) {
                    User user1 = (User) request.getSession().getAttribute("User");
                } else {
                    System.out.println("session 不存在");
                }
                return ResponseData.success("登录成功", user);
            } else {
                return ResponseData.fail("密码错误");
            }
        } else {
            return ResponseData.fail("用户名不存在");
        }
    }


    /**
     * 用户注册
     * @param account
     * @param password
     * @param repassword
     * @return 注册成功则返回数据，失败则返回提示信息
     */
    @RequestMapping(value = "/insertUser", method = RequestMethod.POST)
    @ApiOperation(value = "用户注册", notes = "将信息封装成用户实体类进行注册")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "account", value = "用户账号", required = true),
            @ApiImplicitParam(name = "password", value = "用户密码", required = true),
            @ApiImplicitParam(name = "repassword", value = "重复用户密码", required = true)
    })
    //@ApiParam(value = "用户账号",name ="account" )
    @ResponseBody
    public ResponseData<User> insertUser(@RequestParam String account,
                                         @RequestParam String password,
                                         @RequestParam String repassword) {
        if (password.equals(repassword)) {
            User user = new User();
            user.setAccount(account);
            user.setPassword(password);
            if (userService.checkAccount(account) != null) {
                return ResponseData.fail("账号已存在");
            } else {
                userService.insertUser(user);
                return ResponseData.success("注册成功", user);
            }

        }
        return ResponseData.fail("两次输入密码不一致");

    }

    /**
     * 用户退出登录
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/outLogin", method = RequestMethod.POST)
    @ApiOperation(value = "用户退出登录")
    @ResponseBody
    public ResponseData outLogin(HttpServletRequest request) {
        //清除登陆时的“User”  session对象
        request.removeAttribute("User");
        request.getSession().invalidate();
        return ResponseData.success("已退出登录");
    }

    /**
     * 修改密码
     * @param id
     * @param oldPassword
     * @param newPassword
     * @param rePassword
     * @return
     */
    @RequestMapping(value = "/updateAccountPassword", method = RequestMethod.POST)
    @ApiOperation(value = "用户修改密码", notes = "根据用户id修改自己的密码")
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户id", type = "Integer", required = true),
            @ApiImplicitParam(name = "oldPassword", value = "旧密码", required = true),
            @ApiImplicitParam(name = "newPassword", value = "新密码", required = true),
            @ApiImplicitParam(name = "rePassword", value = "重复密码", required = true)
    })
    public ResponseData updateAccountPassword(Integer id,
                                              String oldPassword,
                                              String newPassword,
                                              String rePassword,
                                              HttpServletRequest request) {
        if (rePassword.equals(newPassword)) {
            User user = userService.queryUserById(id);
            if (oldPassword.equals(user.getPassword())) {
                //修改密码的操作
                userService.updateUserPassword(id, newPassword);
                //清除成功，要求其重新登录 在此时清除session
                request.getSession().invalidate();
                return ResponseData.success("修改密码成功", user);
            } else {
                return ResponseData.fail("修改密码失败");
            }
        } else {
            return ResponseData.fail("两次密码不一致");
        }
    }


    /**
     * 用户修改个人信息
     *
     * @param user,id
     * @return 修改成功返回新的数据，修改失败返回原数据
     */
    @RequestMapping(value = "/updateAccount", method = RequestMethod.POST)
    @ApiOperation(value = "用户修改个人信息", notes = "根据id查询用户信息并进行修改操作1")
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户id", dataType = "int"),
            @ApiImplicitParam(name = "user", value = "封装的用户信息", dataType = "User")
    })
    public ResponseData updateAccount(User user, @ApiIgnore HttpServletRequest req) {
        //从session中获取到的users
        User users = (User) req.getSession().getAttribute("User");
        int nums = userService.checkNickName(user.getNickname());

        if (nums > 0) {
            if (users.getNickname() == null || "".equals(users.getNickname())) {
                return ResponseData.fail("该昵称已被占用");
                //表示老用户修改个人信息，但不包括昵称
            } else if (users.getNickname().equals(user.getNickname())) {
                if (userService.updateUser(user) > 0) {
                    //标识用户的个人信息修改成功
                    HttpSession session = req.getSession(true);
                    user.setSrc(users.getSrc());
                    user.setVip(users.getVip());
                    user.setPassword(users.getPassword());
                    user.setFans(users.getFans());
                    user.setFollow(users.getFollow());
                    user.setPaytime(users.getPaytime());
                    user.setRealname(users.getRealname());
                    user.setAge(users.getAge());
                    session.setAttribute("User", user);
                    return ResponseData.success("修改信息成功", user);
                } else {
                    return ResponseData.fail("修改失败1");
                }
            }
            return ResponseData.fail("该昵称已被占用");
        } else {
            if (userService.updateUser(user) > 0) {
                //标识用户的个人信息修改成功

                HttpSession session = req.getSession(true);
                user.setSrc(users.getSrc());
                user.setVip(users.getVip());
                user.setPassword(users.getPassword());
                user.setFans(users.getFans());
                user.setFollow(users.getFollow());
                user.setAge(users.getAge());
                user.setPaytime(users.getPaytime());
                user.setRealname(users.getRealname());
                session.setAttribute("User", user);
                return ResponseData.success("修改信息成功", user);
            } else {
                return ResponseData.fail("修改失败2");
            }
        }
    }

    /**
     * 用户注销账户
     *
     * @param id
     * @param password
     * @return 注销成功则返回提示信息, 失败则返回原用户数据
     */
    @RequestMapping(value = "/deleteAccount", method = RequestMethod.DELETE)
    @ApiOperation(value = "用户注销", notes = "用户通过密码验证来注销账户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户id"),
            @ApiImplicitParam(name = "password", value = "密码", required = true)
    })
    @ResponseBody
    public ResponseData deleteAccount(Integer id, String password, HttpServletRequest request) {
        User user = userService.queryUserById(id);
        if (password.equals(user.getPassword())) {
            userService.deleteAccount(id, password);
            //注销成功 清除session
            request.getSession().invalidate();
            return ResponseData.success("注销成功", user);
        }
        return ResponseData.fail("密码不正确,注销失败", user);
    }

    /**
     * 登录时判断用户是否是vip
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/judgeVip", method = RequestMethod.POST)
    @ApiOperation(value = "判定用户vip是否到期", notes = "根据当前时间计算用户vip是否过期")
    @ResponseBody
    @ApiImplicitParam(name = "id", value = "用户id", required = true)
    public ResponseData judgeVip(Integer id) {
        User user = userService.queryUserById(id);
        //获取现在的时间
        DateTime dateTime = new DateTime();
        //将字符串转化为DateTime格式
        DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
        DateTime dateTime1 = DateTime.parse(user.getPaytime(), format);
        //计算两个日期间隔的天数
        int days = Days.daysBetween(dateTime, dateTime1).getDays();
        if (days >= 0) {
            return ResponseData.success("vip用户未过期");
        } else {
            //修改用户vip状态为0
            userService.setVip(id, "", 0);
            return ResponseData.fail("用户vip已过期");
        }
    }


}
